from django.shortcuts import render , HttpResponse
from django.views import View
from verfications.PictureCode import CodeImg
from django_redis import get_redis_connection
from utils.response_code import RETCODE
from django.http import JsonResponse
import random
from verfications.mobile_message.cpp_sms import send_code


# 生成图片验证码
class ImageCodeView(View):
    def get(self , request , uuid):
        # 获得验证码 以及图片
        image , code = CodeImg.create_img()

        # 将数据保存到redis数据库
        redis_conn = get_redis_connection('var_code')
        redis_conn.setex('image_%s'%uuid , 400 , code)
        return HttpResponse(image , content_type='image/png')

# 发送短信验证码
class SmsCodeView(View):
    def get(self , request , mobile):
        # 校验图片验证码是否正确

        # 接受参数中的uuid , 以及图片验证码
        uuid = request.GET.get('uuid')
        image_code_client = request.GET.get('image_code')

        # 校验数据是否完整
        if not all([uuid , image_code_client]):
            return HttpResponse("参数有误")


        # 获取redis中的验证码 , 进行验证码的校验
        redis_conn = get_redis_connection('var_code')
        image_code_server = redis_conn.get('image_%s'%uuid)

        send_flag = redis_conn.get('send_%s' % mobile)

        if send_flag:
            return JsonResponse({
                'code': RETCODE.THROTTLINGERR,
                'code_errmsg': '发送短信验证码过于频繁'
            })

        # 判断图片验证码是否过期
        if image_code_server is None:
            return JsonResponse({
                "code":RETCODE.IMAGECODEERR,
                "code_errmsg":"图片验证码失效"
            })
        # 删除图片验证码
        redis_conn.delete('image_%s'%uuid)

        # 判断图片验证码是否正确
        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return JsonResponse({
                "IMAGECODEERR":RETCODE.IMAGECODEERR,
                "code_errmsg":"图片验证码错误"
            })

        # 发送短信验证码
        # 随机生成四位数验证码
        sms_code = random.randint(1000, 9999)
        redis_conn.setex('image_%s' % mobile, 400, sms_code)

        # 创建手机表示
        redis_conn.setex('send_%s' % mobile, 60, 1)

        send_code.send_message(mobile=mobile , datas=(sms_code , 5))

        return JsonResponse({
            "code":RETCODE.OK,
            "code_errmsg":"短信验证码发送成功"
        })









